// components/auth/auth.js
import {  HTTP } from '../../utils/http.js'
let http = new HTTP()
const app = getApp();

Component({
  properties: {},
  data: {
    is_auth: false, //是否已授权
  },
  lifetimes: {},

  methods: {
    //已登陆
    goOn() {
      this.triggerEvent('flagEvent', {});
    },
    //授权
    bindGetUserInfo (e) {
      console.log('eeeeeeee',e)
      if (e.detail.userInfo) {
        this.getUserInfo(e);
      } else {
        console.log('用户点击了“拒绝授权”')
      }
    },

    //获取用户信息接口
    getUserInfo: function(e) {
      let that = this;
      console.log('auth-eeeeee', e)
      wx.login({
        success(res) {
          console.log(res)
          console.log('login-eeeee', res)
          let code = res.code;
          console.log('code-eeeeee',code)
          if(res.code){
            // 存入登陆状态，传入code, rawData, signature, encryptData.
            wx.request({
              url: app.globalData.baseRestUrl + '/user/wxlogin',
              // url: that.tokenUrl,
              method: "POST",
              dataType: "json",
              data: {
                code,
                rawData: e.detail.rawData,
                signature: e.detail.signature,
                iv: e.detail.iv,
                encryptedData: e.detail.encryptedData,
                loginType:'login'
              },
              header: {
                'content-type': 'application/json',
         
              },
              success: (res) => {
                // console.log("调用接口wxlogin-eeeeeeee", res.data.data.token.access_token)
                if( res.data.code === 200){
                  wx.setStorageSync("nickName", res.data.data.nickName);
                  wx.setStorageSync("avatarUrl", res.data.data.avatarUrl);
                  wx.setStorageSync('is_auth', true)
                  wx.setStorageSync('token',res.data.data.token.access_token);
                  wx.setStorageSync('is_member', res.data.data.is_member)
                  that.setData({
                    is_auth: true
                  })

                  that.triggerEvent('flagEvent', {});//登录成功后继续执行
                  // 获取地址授权
                  let address = wx.getStorageSync('address');
                  if(!address){
                    app.login();
                  }
                }else{
                  if(res.data.code === 401){
                    if (!is_auth) {
                      that._refetch(res);
                    }
                  }
                  console.log('error',res)
                }
              },
              fail: (err) => {
                console.log('error',err)
              }
            });
          }
        },
    

      });
    },
  }
})